﻿package rmhc.server
{
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
		
	public class FileUploader extends URLLoader
	{
		protected const rn:String = "\r\n";
		
		protected var boundary:String;
		protected var content:Vector.<MultipartEntry> = new Vector.<MultipartEntry>();
		
		protected var url:String;
		
		public function FileUploader( url:String = null )
		{
			this.url = url;
			
			boundary = "";
			for ( var i:int = 0 ; i < 32 ; i++ )
			{
				boundary += String.fromCharCode( int( 97 + Math.random() * 25 ) );
			}
		}
		
		/*protected function br ():void
		{
			content.writeShort( 0x0d0a );
		}*/
		public function addVar( name:String , value:String ):void
		{
			content.push( new MultipartEntry( name , value ) );
		}
		public function addFile( name:String , filename:String , data:ByteArray , type:String = "application/octet-stream" ):void
		{
			content.push( new FileEntry( name , filename , data , type ) );
		}
		public function remEntry( name:String ):void
		{
			for ( var i:int = 0 ; i < content.length; i++ )
			{
				if ( content[i].name == name )
				{
					content.splice( i , 1 );
				}
			}
		}
		
		public function getData():ByteArray
		{
			var res:ByteArray = new ByteArray();
			res.endian = Endian.BIG_ENDIAN;
			
			for each ( var entry:MultipartEntry in content )
			{
				entry.appendTo( res , boundary );
			}
			
			res.writeUTFBytes( "--" + boundary + "--" + rn );
			return res;
		}
		public function getContentType():String
		{
			//return 'Content-Type: multipart/form-data; boundary="' + boundary + '"';
			return 'multipart/form-data; boundary=' + boundary;
		}
		
		public function getRequest( url:String = null ):URLRequest
		{
			var ru:String = url != null ? url : this.url;
			var req:URLRequest = new URLRequest( ru );
			req.data = getData();
			req.contentType = getContentType();
			req.method = URLRequestMethod.POST;
			return req;
		}
		
		public override function load( request:URLRequest ):void
		{
			var req:URLRequest = request != null ? request : getRequest();
			//Stamper.debug( 'LOAD: ' + ( req.data as ByteArray ).length + " bytes\n" );//+ ( req.data as ByteArray ).toString() +  );
			super.load( req );
		}
	}
}